﻿using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System;
using System.Data;
using System.IO;

namespace DataServer
{
    /// <summary>
    /// 向客户端发送信息类
    /// </summary>
    public class SendClient
    {
        /// <summary>
        /// 调试程序信息
        /// </summary>
        private string debugInfo;
        public string DebugInfo
        {
            get { return debugInfo; }
            set { debugInfo = value; }
        }
        /// <summary>
        ///服务器计算的CRC校验码
        /// </summary>
        private string strServerCRC;
        public string StrServerCRC
        {
            get { return strServerCRC; }
            set { strServerCRC = value; }
        }
        /// <summary>
        /// 接收到客户端字节数组
        /// </summary>
        private byte[] reDataByte;        
        public byte[] ReDataByte
        {
            get { return reDataByte; }
            set { reDataByte = value; }
        }
        /// <summary>
        /// 接收数据的长度
        /// </summary>
        private int reDataLenght;        
        public int ReDataLenght
        {
            get { return reDataLenght; }
            set { reDataLenght = value; }
        }
        /// <summary>
        /// 接收到客户端的十六进制信息
        /// </summary>
        private string _receiveDataHex;
        public string ReceiveDataHex
        {
            get { return _receiveDataHex; }
            set { _receiveDataHex = value; }
        }
       
        /// <summary>
        /// 接收到客户端的信息
        /// </summary>
        private string _receiveData;
        public string ReceiveData
        {
            get { return _receiveData; }
            set { _receiveData = value; }
        }
        /// <summary> 
        /// 发送命令文本常量 
        /// </summary> 
        private string _sendText;
        public string SendText
        {
            get { return _sendText; }
            set { _sendText = value; }
        }
        /// <summary>
        /// 向客户端发送的Socket
        /// </summary>
        private Socket _sendSocket;
        public Socket SendSocket
        {
            get { return _sendSocket; }
            set { _sendSocket = value; }
        }
        /// <summary>
        /// 客户端信息
        /// </summary>
        private EndPoint _clientPoint;
        public EndPoint ClientPoint
        {
            get { return _clientPoint; }
            set { _clientPoint = value; }
        }
        /// <summary>
        /// 解析客户端信息，并向相关变量(客户端发送内容、回发内容)赋值
        /// </summary>
        private void ViewDataInfo() { 
            //解析客户端内容(十六进制)
            ReceiveDataHex = DataUtility.ByteArrayToHexString(ReDataByte, ReDataLenght);
            //客户端CRC十六进制显示
            byte[] rData = new byte[2];
            Array.Copy(ReDataByte, ReDataLenght-2, rData, 0, 2);
            string cCRCStr = DataUtility.ByteArrayToHexString(rData, 2);
            //客户端内容
            ReceiveData = Encoding.Default.GetString(ReDataByte, 0, ReDataLenght - 2) + cCRCStr;//Encoding.ASCII
        }
        /// <summary>
        /// 向客户端发送信息
        /// </summary>
        public void SendClientMgs()
        {
            ViewDataInfo();//转换显示信息
            byte[] rBytedata = ReDataByte;
            int dataLength = reDataLenght;       

            //计算CRC校验码
            byte[] calculatedCRC = CRCUtility.CalculateCRC(ref rBytedata, rBytedata.Length - 2);
            StrServerCRC = DataUtility.ByteArrayToHexString(calculatedCRC, 2);

            bool key = CRCUtility.CheckCRC(ref rBytedata, dataLength);
            if (key)
            {
                string rData = this.ReceiveData;
                ////验证通过,调试看需要将十六进制数据转成字符串
                //string convertData = DataUtility.HexDecode(rData);
                if (rData.Length > 10)
                {
                    string orderCode = rData.Substring(0, 10);
                    switch (orderCode)
                    {
                        case "***TERLIST":
                            this.SendText = GetTreeList();
                            break;
                        case "***UPLOADF":
                            UploadFile();
                            break;
                        case "***GETTEIP":
                            QueryClientIP();
                            break;
                    }
                }
            }
            else {
                byte[] data = Encoding.Default.GetBytes("***ERROR  ");
                SendSocket.SendTo(data, data.Length, SocketFlags.None, ClientPoint);
            }
        }
        /// <summary>
        /// 依据用户名与密码验证正确性
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <returns></returns>
        private bool CheckUserInfo(string userName, string userPwd)
        {
            //Program.Cache.Get("UserName");
            return true;
        }
        /// <summary>
        /// 获取树型目录数据格式
        /// </summary>
        /// <returns></returns>
        private string GetTreeList()
        {
            string usserName = this.ReceiveData.Substring(10, 10);
            string usserPwd = this.ReceiveData.Substring(20, 10);
            return "***TERLIST测试123";
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        private void UploadFile()
        {
            //存储路径
            string filePath = System.Configuration.ConfigurationManager.AppSettings["UploadFilePath"];
            string saveFile = filePath + "asd.jpg";

            //long len = 0L;

            //byte[] fileByte;
            //long length = long.Parse(Encoding.Unicode.GetString(fileByte));

            //while (len < length)
            //{
            //    byte[] bytes = udp.Receive(ref iep);
            //    Console.WriteLine("{0}", i++);
            //    fs.Write(bytes, 0, bytes.Length);
            //    len += bytes.Length;
            //}


            //FileStream fs = new FileStream(saveFile, FileMode.OpenOrCreate, FileAccess.Write);   //注意这个的属性和send端有所不同
            //BinaryWriter binarywrite = new BinaryWriter(fs);
            //int count;
            //byte[] b = new byte[4098];
            //while ((count = s.Receive(b, 4098, SocketFlags.None)) != 0)             //这个是接受文件流
            //{
            //    binarywrite.Write(b, 0, count);                          //将接收的流用写成文件
            //}
            //binarywrite.Close();
            //fs.Close();
        }
        /// <summary>
        /// 查询终端IP
        /// </summary>
        /// <returns></returns>
        private void QueryClientIP()
        {
            //获取客户端请求的终端ID
            byte[] cRquestId = new byte[2];
            Array.Copy(this.reDataByte, 10, cRquestId, 0, 2);
            Array.Reverse(cRquestId);//反转数组转成大端
            ushort cRqestNum = BitConverter.ToUInt16(cRquestId, 0);//得到要查询的终端ID
            DebugInfo = "查询终端ID:"+cRqestNum;
            //根据终端ID进行查询
            DataTable dt = (DataTable)Program.Cache.Get("ClientDatable");
            if (dt == null) {
                ReadClientFile readInfo = new ReadClientFile();
                readInfo.LoadClientInfo();
                dt = (DataTable)Program.Cache.Get("ClientDatable");
            }
            DataRow[] clientRow=dt.Select("cId='"+cRqestNum+"'");

            byte[] sendByte;// = new byte[20];//发送的字节数组
            if (clientRow.Length > 0)
            {
                sendByte = new byte[20];
                //Order
                string order = "***GETTEIP";
                byte[] mybyte = Encoding.Default.GetBytes(order);
                Array.Copy(mybyte, 0, sendByte, 0, 10);//向指定位置追加
                //ClientNumber
                //ushort clientNumber = 42794;//终端号
                byte[] cNumber = BitConverter.GetBytes(cRqestNum);
                Array.Copy(cNumber, 0, sendByte, 10, 2);
                //IP
                string ip = clientRow[0][1].ToString();
                string[] ips = ip.Split('.');
                byte[] ipByte = new byte[4];
                ipByte[0] = byte.Parse(ips[0]);
                ipByte[1] = byte.Parse(ips[1]);
                ipByte[2] = byte.Parse(ips[2]);
                ipByte[3] = byte.Parse(ips[3]);
                Array.Copy(ipByte, 0, sendByte, 12, 4);
                //Port
                string sPort = clientRow[0][2].ToString();
                ushort uPort = ushort.Parse(sPort);
                byte[] bPort = System.BitConverter.GetBytes(uPort);
                Array.Copy(bPort, 0, sendByte, 16, 2);
                //CRC
                byte[] crc = CRCUtility.CalculateCRC(ref sendByte, 18);
                Array.Copy(crc, 0, sendByte, 18, 2);
            }
            else {
                string order = "***ERROR  ";
                sendByte = Encoding.Default.GetBytes(order);
            }
            this.SendText = DataUtility.ByteArrayToHexString(sendByte, sendByte.Length);
            SendSocket.SendTo(sendByte, sendByte.Length, SocketFlags.None, ClientPoint);

        }
    }
}